import React, { useState } from 'react'
import Ticketiltem from './Ticketiltem'
import { useLoaderData, useSearchParams } from 'react-router-dom'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'
import { getTicketListApi } from '../../../api/ticket'
import {  List as VirtualizedList,AutoSizer, WindowScroller,} from 'react-virtualized'

const TicketList = () => {
    const { list } = useLoaderData()
    // console.log(list);

    const [page, setPage] = useState(1)
    const [sp] = useSearchParams()
    const [trainList, setTrainList] = useState(list)
    const [hasMore, setHasMore] = useState(true)
    async function loadMore() {
        // console.log('ok, 触底了, 执行了 loadMore 函数');
        const data1 = Object.fromEntries(sp)
        const data2 = { page: page + 1, ...data1 }
        // console.log(data1);

        const { data: res } = await getTicketListApi(data2)
        setTrainList((prev) => [...prev, ...res])
        setPage((prev) => prev + 1)

        if (res.length === 0) {
            setHasMore(false)
        }
    }

    const onRefresh = async () => {
        console.log('触发了下拉刷新');
        const data = Object.fromEntries(sp)
        const { data: res } = await getTicketListApi(data)
        setTrainList(res)
        setPage(1)
        setHasMore(true)
    }

    function rowRenderer({index,key,style}) {
        const item = trainList[index]
        if (!item) return

        return (
            <div
             style={style}
             key={key}
            >
            <Ticketiltem {...item}/>
            </div>
        )
    }

    return (
        <div>
            <PullToRefresh onRefresh={onRefresh}>
                {/*
             {
                trainList.map((v) => {
                    
                    return <Ticketiltem
                        key={v.id}
                        {...v}
                    />
                })}
            */}
                <WindowScroller>
                    {({ height, scrollTop, isScrolling }) => (
                        <AutoSizer disableHeight>
                            {({ width }) => (
                                <VirtualizedList
                                    autoHeight
                                    rowCount={trainList.length}
                                    rowRenderer={rowRenderer}
                                    width={width}
                                    height={height}
                                    rowHeight={85}
                                    overscanRowCount={10}
                                    isScrolling={isScrolling}
                                    scrollTop={scrollTop}
                                />
                            )}
                        </AutoSizer>
                    )}
                </WindowScroller>
            </PullToRefresh>
            <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
        </div>
    )
}

export default TicketList
